package com.gjl.web.controller.system;

import com.gjl.common.core.domain.AjaxResult;
import com.gjl.common.core.domain.entity.SysUser;
import com.gjl.common.core.domain.model.WxLoginBody;
import com.gjl.common.core.domain.model.response.WxLoginResponse;
import com.gjl.framework.web.service.TokenService;
import com.gjl.framework.web.service.WxLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName : WxLoginController
 * @Description : TODO
 * @Author : liuhui.jiao
 * @Date: 2025/10/28 22:19
 */
@Api("微信登录")
@RestController
public class WxLoginController {

    @Autowired
    WxLoginService wxLoginService;

    @Autowired
    TokenService tokenService;

    // 配置日志操作
    private static final Logger logger = LoggerFactory.getLogger(WxLoginController.class);


    /**
     * 登录方法
     *
     * @param code 登录信息
     * @return 结果
     */
    @ApiOperation("根据微信code获取手机号")
    @GetMapping("/wx/getPhoneByCode")
    public AjaxResult getPhoneByCode(@RequestHeader HttpHeaders headers, String code)
    {
        String openId = headers.getFirst("openId");
        logger.info(" /wx/getPhoneByCode openId:{}", openId);
        // 判断是否存在code
        if (Objects.isNull(code)){
            logger.error(" /wx/login Web Get code error，body");
            return AjaxResult.error("登录失败！");
        }

        // 绑定手机号和openId
        SysUser sysUser = wxLoginService.relatedPhoneAndOpenId(openId,code);
        Map<String, Object> claims = new HashMap<>();
        if (Objects.isNull(sysUser)){
            claims.put("phonenumber", "");
            claims.put("hasPhonenumber", false);
            return AjaxResult.success(claims);
        }
        claims.put("phonenumber", sysUser.getPhonenumber());
        claims.put("hasPhonenumber", true);
        return AjaxResult.success(claims);
    }


    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiOperation("微信登陆")
    @PostMapping("/wx/login")
    public AjaxResult login(@RequestBody WxLoginBody body)
    {
        // 判断已经存在token情况
        if (Objects.isNull(body)){
            logger.error(" /wx/login Web Get code error，body");
            return AjaxResult.error("登录失败！");
        }

        // 生成令牌
        WxLoginResponse login = wxLoginService.login(body);
        if (login == null){
            return AjaxResult.error("登录失败！");
        }

        return AjaxResult.success(login);
    }



}
